<template>
  <a-drawer
    v-if="open"
    title="编辑课程"
    :open="true"
    :maskClosable="false"
    width="634"
    @close="onCancel"
    :footer="footer"
  >
    <div v-if="init" class="float-left text-center mt-30">
      <a-spin></a-spin>
    </div>
    
    <div v-else class="float-left mt-24">
      <SelectRange
        :defaultDepIds="depIds"
        :defaultDeps="deps"
        :open="idsVisible"
        @cancel="setIdsVisible(false)"
        @selected="handleRangeSelected"
      />
      
      <a-form
        ref="formRef"
        :model="formState"
        :label-col="{ span: 5 }"
        :wrapper-col="{ span: 19 }"
        @finish="onFinish"
        @finishFailed="onFinishFailed"
      >
        <!-- 课程分类 -->
        <a-form-item
          label="课程分类"
          name="category_ids"
          :rules="[{ required: true, message: '请选择课程分类!' }]"
        >
          <a-tree-select
            v-model:value="formState.category_ids"
            show-checked-strategy="SHOW_ALL"
            allow-clear
            multiple
            style="width: 424px"
            :tree-data="categories"
            placeholder="请选择课程分类"
            tree-default-expand-all
          />
        </a-form-item>

        <!-- 课程名称 -->
        <a-form-item
          label="课程名称"
          name="title"
          :rules="[{ required: true, message: '请在此处输入课程名称!' }]"
        >
          <a-input
            v-model:value="formState.title"
            allow-clear
            style="width: 424px"
            placeholder="请在此处输入课程名称"
          />
        </a-form-item>

        <!-- 课程属性 -->
        <a-form-item
          label="课程属性"
          name="isRequired"
          :rules="[{ required: true, message: '请选择课程属性!' }]"
        >
          <a-radio-group v-model:value="formState.isRequired">
            <a-radio :value="1">必修课</a-radio>
            <a-radio :value="0" style="margin-left: 22px">选修课</a-radio>
          </a-radio-group>
        </a-form-item>

        <!-- 指派部门 -->
        <a-form-item
          label="指派部门"
          name="type"
          :rules="[{ required: true, message: '请选择指派部门!' }]"
        >
          <a-radio-group v-model:value="formState.type" @change="getType">
            <a-radio value="open">全部部门</a-radio>
            <a-radio value="elective">选择部门</a-radio>
          </a-radio-group>
        </a-form-item>

        <!-- 选择部门 -->
        <a-form-item
          v-if="formState.type === 'elective'"
          label="选择部门"
          name="ids"
          :rules="[{ required: true, message: '请选择部门!' }]"
        >
          <div class="d-flex" style="width: 100%; flex-wrap: wrap; margin-bottom: -8px">
            <a-button type="default" style="margin-bottom: 14px" @click="setIdsVisible(true)">
              添加范围
            </a-button>
            <div class="d-flex" style="width: 100%; flex-wrap: wrap; margin-bottom: -16px">
              <a-tag
                v-for="(item, i) in deps"
                :key="i"
                closable
                :style="{
                  height: '32px',
                  lineHeight: '32px',
                  fontSize: '14px',
                  color: '#FF4D4F',
                  background: 'rgba(255,77,79,0.1)',
                  marginRight: '16px',
                  marginBottom: '16px',
                }"
                @close="(e) => handleTagClose(e, i)"
              >
                {{ item.title }}
              </a-tag>
            </div>
          </div>
        </a-form-item>

        <!-- 课程封面 -->
        <a-form-item
          label="课程封面"
          name="thumb"
          :rules="[{ required: true, message: '请上传课程封面!' }]"
        >
          <div class="d-flex">
            <a-image
              :src="thumb"
              :width="160"
              :height="120"
              :style="{ borderRadius: '6px' }"
              :preview="false"
            />
            <div class="c-flex ml-8 flex-1">
              <div class="d-flex mb-28">
                <div
                  v-for="(defaultThumb, index) in defaultThumbs"
                  :key="index"
                  :class="['thumb-item', { 'thumb-item-active': thumb === defaultThumb }]"
                  @click="handleThumbClick(defaultThumb, index)"
                >
                  <a-image
                    :src="defaultThumb"
                    :width="80"
                    :height="60"
                    :style="{ borderRadius: '6px' }"
                    :preview="false"
                  />
                </div>
              </div>
              <div class="d-flex">
                <UploadImageButton
                  text="更换封面"
                  @selected="handleImageSelected"
                />
                <span class="helper-text ml-8">（推荐尺寸:400x300px）</span>
              </div>
            </div>
          </div>
        </a-form-item>

        <!-- 课程简介 -->
        <a-form-item label="课程简介" name="short_desc">
          <a-textarea
            v-model:value="formState.short_desc"
            style="width: 424px; min-height: 80px"
            allow-clear
            placeholder="请输入课程简介（最多200字）"
            :maxlength="200"
          />
        </a-form-item>

        <!-- 上架时间 -->
        <a-form-item label="上架时间">
          <a-space align="baseline" style="height: 32px">
            <a-form-item name="published_at">
              <a-date-picker
                v-model:value="formState.published_at"
                :disabled-date="disabledDate"
                format="YYYY-MM-DD HH:mm:ss"
                style="width: 240px"
                show-time
                placeholder="请选择上架时间"
              />
            </a-form-item>
            <div class="helper-text">（上架时间越晚，排序越靠前）</div>
          </a-space>
        </a-form-item>
      </a-form>
    </div>
  </a-drawer>
</template>

<script setup lang="ts">
import { ref, reactive, watch, computed, h } from 'vue';
import { 
  Drawer as ADrawer, 
  Form as AForm, 
  Input as AInput, 
  Radio as ARadio, 
  Button as AButton, 
  Image as AImage, 
  Spin as ASpin, 
  Tag as ATag, 
  TreeSelect as ATreeSelect,
  Textarea as ATextarea,
  DatePicker as ADatePicker,
  Space,
  message
} from 'ant-design-vue';
import dayjs from 'dayjs';
import { course, department } from '@/api';
import UploadImageButton from '@/components/Common/upload-image-button.vue';
import SelectRange from '@/components/Common/select-range.vue';
import defaultThumb1 from '@/assets/thumb/thumb1.png';
import defaultThumb2 from '@/assets/thumb/thumb2.png';
import defaultThumb3 from '@/assets/thumb/thumb3.png';

interface Props {
  id: number;
  open: boolean;
  onCancel: () => void;
}

interface Option {
  value: string | number;
  title: string;
  children?: Option[];
}

const props = defineProps<Props>();

const formRef = ref();
const init = ref(true);
const loading = ref(false);
const departments = ref<Option[]>([]);
const categories = ref<Option[]>([]);
const resourceUrl = ref<ResourceUrlModel>({});
const thumb = ref(defaultThumb1);
const defaultThumbs = [defaultThumb1, defaultThumb2, defaultThumb3];
const depIds = ref<number[]>([]);
const deps = ref<Array<{ key: number; title: string }>>([]);
const idsVisible = ref(false);
const type = ref('open');

const formState = reactive({
  title: '',
  thumb: -1,
  category_ids: [] as number[],
  isRequired: 1,
  short_desc: '',
  type: 'open',
  ids: [] as number[],
  published_at: null as any,
});

// 修复：参考创建课程的正确实现
const handleConfirm = async () => {
  if (!formRef.value) return;
  try {
    const values = await formRef.value.validate();
    onFinish(values);
  } catch (err) {
    console.log('表单校验失败', err);
  }
};

const footer = computed(() =>
  h(Space, { class: 'j-r-flex' }, [
    h(AButton, { onClick: props.onCancel }, '取 消'),
    h(AButton, { 
      loading: loading.value, 
      onClick: handleConfirm, 
      type: 'primary' 
    }, '确 认')
  ])
);

// Watchers
watch(() => props.open, (newVal) => {
  if (newVal && props.id !== 0) {
    initData();
  }
});

// Methods
const initData = async () => {
  init.value = true;
  await getParams();
  await getCategory();
  await getDetail();
  init.value = false;
};

const getCategory = async () => {
  try {
    const res: any = await course.createCourse();
    const categoriesData = res.data.categories;
    if (JSON.stringify(categoriesData) !== '{}') {
      const new_arr = checkArr(categoriesData, 0, null);
      categories.value = new_arr;
    }
  } catch (error) {
    console.error('获取分类数据失败:', error);
  }
};

const getParams = async () => {
  try {
    const res: any = await department.departmentList({});
    const departmentsData = res.data.departments;
    const departCount = res.data.dep_user_count;
    if (JSON.stringify(departmentsData) !== '{}') {
      const new_arr = checkArr(departmentsData, 0, departCount);
      departments.value = new_arr;
    }
  } catch (error) {
    console.error('获取部门数据失败:', error);
  }
};

const getDetail = async () => {
  try {
    const res: any = await course.course(props.id);
    const courseData = res.data.course;
    const courseType = res.data.dep_ids.length > 0 ? 'elective' : 'open';
    
    // 设置表单值
    formState.title = courseData.title;
    formState.thumb = courseData.thumb;
    formState.category_ids = res.data.category_ids;
    formState.isRequired = courseData.is_required;
    formState.short_desc = courseData.short_desc;
    formState.type = courseType;
    formState.published_at = courseData.sort_at ? dayjs(courseData.sort_at) : null;
    
    type.value = courseType;
    
    // 设置缩略图
    const thumbSrc = getThumbSrc(courseData.thumb, res.data.resource_url);
    thumb.value = thumbSrc;
    
    // 处理部门数据
    const depsData = res.data.deps;
    if (depsData && JSON.stringify(depsData) !== '{}') {
      getDepsDetail(depsData);
    }
    
    resourceUrl.value = res.data.resource_url;
  } catch (error) {
    console.error('获取课程详情失败:', error);
  }
};

const getThumbSrc = (thumbValue: number, resourceUrl: any) => {
  if (thumbValue === -1) return defaultThumb1;
  if (thumbValue === -2) return defaultThumb2;
  if (thumbValue === -3) return defaultThumb3;
  return resourceUrl[thumbValue] || defaultThumb1;
};

const getDepsDetail = (depsData: any) => {
  const arr: number[] = [];
  const arr2: any[] = [];
  
  Object.keys(depsData).forEach((key) => {
    arr.push(Number(key));
    arr2.push({
      key: Number(key),
      title: depsData[key],
    });
  });
  
  depIds.value = arr;
  deps.value = arr2;
};

const getNewTitle = (title: any, id: number, counts: any) => {
  if (counts) {
    const value = counts[id] || 0;
    return `${title}(${value})`;
  }
  return title;
};

const checkArr = (departments: any[], id: number, counts: any) => {
  const arr = [];
  if (!departments[id]) return arr;
  
  for (let i = 0; i < departments[id].length; i++) {
    const item = departments[id][i];
    if (!departments[item.id]) {
      arr.push({
        title: getNewTitle(item.name, item.id, counts),
        value: item.id,
      });
    } else {
      const new_arr = checkArr(departments, item.id, counts);
      arr.push({
        title: getNewTitle(item.name, item.id, counts),
        value: item.id,
        children: new_arr,
      });
    }
  }
  return arr;
};

const onFinish = async (values: any) => {
  if (loading.value) return;
  
  let dep_ids: any[] = [];
  if (type.value === 'elective') {
    dep_ids = depIds.value;
  }
  
  loading.value = true;
  try {
    await course.updateCourse(
      props.id,
      values.title,
      values.thumb,
      values.short_desc,
      1,
      values.isRequired,
      dep_ids,
      values.category_ids,
      [],
      [],
      values.published_at
    );
    message.success('保存成功！');
    props.onCancel();
  } catch (error) {
    console.error('保存课程失败:', error);
  } finally {
    loading.value = false;
  }
};

const onFinishFailed = (errorInfo: any) => {
  console.log('Failed:', errorInfo);
};

const getType = (e: any) => {
  type.value = e.target.value;
  formState.type = e.target.value;
};

const disabledDate = (current: any) => {
  return current && current >= dayjs().endOf('day');
};

const handleThumbClick = (selectedThumb: string, index: number) => {
  thumb.value = selectedThumb;
  formState.thumb = -(index + 1);
};

const handleImageSelected = (url: string, id: number) => {
  thumb.value = url;
  formState.thumb = id;
};

const handleRangeSelected = (selDepIds: number[], selDeps: any[]) => {
  depIds.value = selDepIds;
  deps.value = selDeps;
  formState.ids = selDepIds;
  idsVisible.value = false;
};

const handleTagClose = (e: Event, index: number) => {
  e.preventDefault();
  deps.value.splice(index, 1);
  depIds.value.splice(index, 1);
  formState.ids = [...depIds.value];
};

// Setters
const setIdsVisible = (visible: boolean) => {
  idsVisible.value = visible;
};
</script>

<style scoped>
.d-flex {
  display: flex;
}

.c-flex {
  display: flex;
  flex-direction: column;
}

.ml-8 {
  margin-left: 8px;
}

.mb-28 {
  margin-bottom: 28px;
}

.mt-24 {
  margin-top: 24px;
}

.mt-30 {
  margin-top: 30px;
}

.flex-1 {
  flex: 1;
}

.float-left {
  float: left;
}

.text-center {
  text-align: center;
}

.helper-text {
  color: #999;
  font-size: 12px;
}

.j-r-flex {
  display: flex;
  justify-content: flex-end;
}

.thumb-item {
  width: 80px;
  height: 60px;
  cursor: pointer;
  margin-right: 8px;
  border-radius: 6px;
  padding: 4px;
  border: 2px solid transparent;
}

.thumb-item:last-child {
  margin-right: 0;
}

.thumb-item-active {
  width: 80px;
  height: 60px;
  border: 2px solid #ff4d4f;
  cursor: pointer;
  margin-right: 8px;
  border-radius: 8px;
  padding: 4px;
}

.thumb-item-active:last-child {
  margin-right: 0;
}
</style>